#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-9-19'
# code is far away from bugs with the god animal protecting ~
"""
from flask import render_template, request, session, redirect, url_for, jsonify, current_app, abort

from info import constants, db
from info.models import User, Category, News
from info.response_code import RET
from info.utils.common import required_login, general_msg
from datetime import datetime
import time

from info.utils.image_storage import storage
from . import bp_admin as app


# 用户登陆页面
@app.route("/", methods=["GET", "POST"])
def admin_login():
	if request.method == "GET":
		return render_template("admin/login.html")
	else:

		print(request.method)
		get_param = request.form
		username = get_param.get("username", None)
		password = get_param.get("password", None)

		if not all([username, password]):
			return general_msg(RET.PARAMERR)

		user = User.query.filter_by(mobile=username).first()

		if any([not user, not user.is_admin, not user.check_password(password)]):
			return general_msg(RET.USERERR)
		else:
			# 用户登录成功,写入Session信息
			session["user_id"] = user.id
			session["mobile"] = user.mobile
			session["nick_name"] = user.nick_name
			session["is_admin"] = user.is_admin

			return general_msg(RET.OK)


# 用户管理首页
@app.route("/index", methods=["GET"])
def index():
	user_id = session.get("user_id", None)
	user = User.query.get(user_id)

	return render_template("admin/index.html", user=user.to_dict())


# 用户计数
@app.route("/user_count", methods=["GET", "POST"])
def user_count():
	now = datetime.now().timetuple()

	now_month = datetime.strptime("%s-%s-1" % (now.tm_year, now.tm_mon), "%Y-%m-%d")
	now_day = datetime.strptime("%s-%s-%s" % (now.tm_year, now.tm_mon, now.tm_mday), "%Y-%m-%d")

	count_all_user = User.query.count()
	count_month_user = User.query.filter(User.create_time >= now_month).count()
	count_day_user = User.query.filter(User.create_time >= now_day).count()

	param = {"count_all_user": count_all_user, "count_month_user": count_month_user, "count_day_user": count_day_user}
	return render_template("admin/user_count.html", **param)


# 用户列表
@app.route("/user_list", methods=["GET"])
def user_list():
	page = request.args.get("page", None)

	is_index = False
	if page:
		try:
			page = int(page)
		except Exception as e:
			return general_msg(RET.PARAMERR)
	else:
		is_index = True

	paginate = User.query.order_by(User.create_time.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
	collections = [user.to_admin_dict() for user in paginate.items]

	if is_index:
		return render_template("admin/user_list.html", collections=collections, total_page=paginate.pages,
							   curr_page=paginate.page)
	else:
		param = {"errno": RET.OK, "total_page": paginate.pages, "collections": collections}
		return jsonify(param)


# 用户审核
@app.route("/news_review", methods=["GET", "POST"])
def news_review():
	if request.method == "GET":
		# 如果是GET请求，则反回主页的数据，默认返回第一页，如果有页码参数，则响应第几页数据
		page = request.args.get("page",None)

		is_index = False
		if page:
			try:
				page = int(page)
			except Exception as e:
				return general_msg(RET.PARAMERR)
		else:
			is_index = True

		paginate = News.query.order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
		collections = [news.to_review_dict() for news in paginate.items]

		if is_index:
			return render_template("admin/news_review.html", collections=collections, total_page=paginate.pages, curr_page=paginate.page)
		else:
			param = {"errno": RET.OK, "total_page": paginate.pages, "collections": collections}
			return jsonify(param)

	else:
		# 如果是POST请求，则反回搜索的数据
		search_name = request.form.get("searchname")
		if not search_name:
			return redirect(url_for("bp_admin.news_review"))

		paginate = News.query.filter(News.title.like("%" + search_name + "%")).order_by(News.create_time.desc()).paginate(1, constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
		collections = [news.to_review_dict() for news in paginate.items]

		return render_template("admin/news_review.html", collections=collections, total_page=paginate.pages, curr_page=paginate.page)


# 用户审核详细界面
@app.route("/news_review_detail", methods=["GET", "POST"])
def news_review_detail():

	if request.method == "GET":
		news_id = request.args.get("newsid", None)
		if news_id :
			try:
				news_id = int(news_id)
			except Exception as e:
				abort(404)

			categorys = Category.query.filter(Category.id>1).all()
			categorys = [category.to_dict() for category in categorys]
			news = News.query.get(news_id)
			return render_template("admin/news_review_detail.html", news=news.to_dict(), categorys=categorys)
		else:
			abort(404)
	else:
		get_param = request.form
		news_id = get_param.get("news_id")
		action = get_param.get("action")
		reason = get_param.get("reason")

		if not all([news_id, action]):
			return general_msg(RET.PARAMERR)

		try:
			news_id = int(news_id)
		except Exception:
			return general_msg(RET.PARAMERR)

		news = News.query.get(news_id)
		if action == "accept":
			news.status = 1
		elif action == "reject":
			if reason:
				news.reason = reason
				news.status = -1
			else:
				return general_msg(RET.PARAMERR)

		try:
			db.session.add(news)
			db.session.commit()
		except Exception as e:
			db.session.rollback()
			current_app.logger.error(e)
			return general_msg(RET.DBERR)

		return general_msg(RET.OK)


# 新闻编辑
@app.route("/news_edit", methods=["GET", "POST"])
def news_edit():
	if request.method == "GET":
		# 如果是GET请求，则反回主页的数据，默认返回第一页，如果有页码参数，则响应第几页数据
		page = request.args.get("page",None)

		is_index = False
		if page:
			try:
				page = int(page)
			except Exception as e:
				return general_msg(RET.PARAMERR)
		else:
			is_index = True

		paginate = News.query.order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
		collections = [news.to_review_dict() for news in paginate.items]

		if is_index:
			return render_template("admin/news_edit.html", collections=collections, total_page=paginate.pages, curr_page=paginate.page)
		else:
			param = {"errno": RET.OK, "total_page": paginate.pages, "collections": collections}
			return jsonify(param)

	else:
		# 如果是POST请求，则反回搜索的数据
		search_name = request.form.get("searchname")
		if not search_name:
			return redirect(url_for("bp_admin.news_edit"))

		paginate = News.query.filter(News.title.like("%" + search_name + "%")).order_by(News.create_time.desc()).paginate(1, constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
		collections = [news.to_review_dict() for news in paginate.items]

		return render_template("admin/news_edit.html", collections=collections, total_page=paginate.pages, curr_page=paginate.page)


# 用户编辑详细界面
@app.route("/news_edit_detail", methods=["GET", "POST"])
def news_edit_detail():

	if request.method == "GET":
		news_id = request.args.get("newsid", None)
		if news_id :
			try:
				news_id = int(news_id)
			except Exception as e:
				abort(404)

			categorys = Category.query.filter(Category.id>1).all()
			categorys = [category.to_dict() for category in categorys]
			news = News.query.get(news_id)
			return render_template("admin/news_edit_detail.html", news=news.to_dict(), categorys=categorys)
		else:
			abort(404)
	else:
		get_param = request.form
		news_id = get_param.get("news_id")
		title =  get_param.get("title")
		digest = get_param.get("digest")
		content = get_param.get("content")
		# 取文件，要另外选
		file_image = request.files.get("index_image_url", None)
		category_id = get_param.get("category_id")

		if file_image:
			try:
				index_image_url = constants.QINIU_DOMIN_PREFIX + storage(file_image.read())
			except Exception as e:
				current_app.logger.error(e)
				return general_msg(RET.THIRDERR)
		else:
			index_image_url = None

		try:
			news_id = int(news_id)
			category_id = int(category_id)
		except Exception:
			return general_msg(RET.PARAMERR)

		news = News.query.get(news_id)

		if index_image_url:
			news.index_image_url = index_image_url

		if title:
			news.title = title

		if digest:
			news.digest = digest

		if content:
			news.content = content

		if category_id:
			news.category_id = category_id

		try:
			db.session.add(news)
			db.session.commit()
		except Exception as e:
			db.session.rollback()
			current_app.logger.error(e)
			return general_msg(RET.DBERR)

		return general_msg(RET.OK)


# 新闻类型
@app.route("/news_type", methods=["GET", "POST"])
def news_type():
	if request.method == "GET":
		categorys = Category.query.filter(Category.id > 1).all()
		return render_template("admin/news_type.html", categorys=categorys)
	else:
		get_param = request.json
		type_id = get_param.get("id", None)
		type_name =get_param.get("name", None)
		type_action =get_param.get("action", None)

		# 如果有ID，则做删除和修改操作
		if type_id:
			category = Category.query.get(int(type_id))

			if category:
				# 删除
				if type_action == "delete" :
					try:
						db.session.delete(category)
						db.session.commit()
					except Exception as e:
						db.session.rollback()
						current_app.logger.error(e)
						return general_msg(RET.DBERR)

				# 修改类型名
				elif type_name:
					category.name = type_name
					try:
						db.session.add(category)
						db.session.commit()
					except Exception as e:
						db.session.rollback()
						current_app.logger.error(e)
						return general_msg(RET.DBERR)
			else:
				return general_msg(RET.RET.NODATA, "新闻类型错误")

		else:
			# 没有ID就新增一个类型
			if type_name:
				category = Category()
				category.name = type_name
				try:
					db.session.add(category)
					db.session.commit()
				except Exception as e:
					db.session.rollback()
					current_app.logger.error(e)
					return general_msg(RET.DBERR)
			else:
				return general_msg(RET.PARAMERR, "没有输入新闻类型")

		return general_msg(RET.OK)


if __name__ == '__main__':
	pass
